package com.inhim.pjhim.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.inhim.pjhim.R;
import com.inhim.pjhim.adapter.ProjectRadioListAdapter;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.app.MyApplication;
import com.inhim.pjhim.entity.ProjectListEntity;
import com.inhim.pjhim.entity.ReaderStyle;
import com.inhim.pjhim.entity.ReaderTypeList;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.utils.PrefUtils;
import com.inhim.pjhim.utils.StatusBarUtils;
import com.pili.pldroid.player.AVOptions;

import org.yczbj.ycrefreshviewlib.inter.InterItemView;
import org.yczbj.ycrefreshviewlib.view.YCRefreshView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCMediaManager;
import fm.jiecao.jcvideoplayer_lib.JCRadioPlayer;
import fm.jiecao.jcvideoplayer_lib.JCRadioPlayerStandard;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;
import okhttp3.Request;

public class ProjectRadioListActivity extends BaseActivity implements ProjectRadioListAdapter.NotifyPositionListener{
    private YCRefreshView ycRefreshView;
    private ReaderStyle.List readerstyle;
    private ReaderTypeList.List readerType;
    private ProjectRadioListAdapter mAdapter;
    private int mPageNum = 1;
    private Boolean refresh = true;
    private int totalPage;
    private Gson gson;
    private String TAG;
    JCRadioPlayerStandard mJcVideoPlayerStandard;
    private List<ProjectListEntity.List> radioInfoList;
    private boolean mIsLiveStreaming = false;
    private String mOrder;
    private int mReaderTypeId;
    private int mPlayPosition;
    @Override
    public Object offerLayout() {
        return R.layout.activity_project_radio_list;
    }

    @SuppressLint("NewApi")
    @Override
    public void onBindView() {
        gson = new Gson();
        mPlayPosition=0;
        ycRefreshView = findViewById(R.id.ycRefreshView);
        mJcVideoPlayerStandard = findViewById(R.id.jc_video);
        View statusBar = findViewById(R.id.statusBarView);
        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
        layoutParams.height = MyApplication.getStatusBarHeight();
        View navigationView = findViewById(R.id.navigationView);
        ViewGroup.LayoutParams navigationlayoutParams = navigationView.getLayoutParams();
        if(StatusBarUtils.isHaveNativBar(this)){
            navigationlayoutParams.height = MyApplication.getNavigationBarHeight();
        }else{
            navigationlayoutParams.height = 0;
        }
        readerstyle = (ReaderStyle.List) getIntent().getSerializableExtra("ReaderStyle");
        readerType = (ReaderTypeList.List) getIntent().getSerializableExtra("ReaderTypeList");
        TAG = getIntent().getStringExtra("TAG");
        mReaderTypeId=getIntent().getIntExtra("readerTypeId",0);
        mOrder="asc";
        initAdapter();
        getReaderList();
    }

    @Override
    public void destory() {
        mMainHander.removeCallbacksAndMessages(null);
        if(!JCMediaManager.instance().mediaPlayer.isPlaying()){
            hideFloat();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initAdapter() {
        //TextView tv_title = findViewById(R.id.tv_title);
        TextView tv_title_top = findViewById(R.id.tv_title_top);
        TextView tv_content = findViewById(R.id.tv_content);
        TextView tv_section = findViewById(R.id.tv_section);
        check_play = findViewById(R.id.check_play);
        RadioButton tv_new_update=findViewById(R.id.tv_new_update);
        RadioButton tv_noramal_sort=findViewById(R.id.tv_noramal_sort);
        TextView tv_zuozhe=findViewById(R.id.tv_zuozhe);
        if(readerType.getAuthor()!=null&& readerType.getAuthor().getName()!=null){
            tv_zuozhe.setText("作者："+readerType.getAuthor().getName());
        }
        check_play.setOnClickListener(v-> {
            if(!check_play.isChecked()){
                hideFloat();
            }else{
                if(JCMediaManager.instance().mediaPlayer.isPlaying()){
                    JCRadioPlayer.releaseAllVideos();
                    mAdapter.setFirst(false);
                }
            }
            setRadio(mPlayPosition);
            plarRadio(check_play.isChecked(),mPlayPosition);
            mAdapter.setPlayPosition(mPlayPosition,check_play.isChecked());
            mAdapter.notifyDataSetChanged();
        });
        //CheckBox iv_down=headerView.findViewById(R.id.cb_down);
        setText(tv_title_top, readerType.getName());
        setText(tv_content, readerType.getSynopsis());
        setText(tv_section, "共" + readerType.getTotal() + "课");
        tv_new_update.setOnClickListener(v -> {
            refresh=true;
            mOrder="desc";
            getReaderList();
        });
        tv_noramal_sort.setOnClickListener(v -> {
            refresh=true;
            mOrder="asc";
            getReaderList();
        });
        ImageView iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mAdapter = new ProjectRadioListAdapter(ProjectRadioListActivity.this);
        try{
            if(JCMediaManager.instance().mediaPlayer.isPlaying()){
                mAdapter.setFirst(true);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        mAdapter.setNotifyPositionListener(this);
        ycRefreshView.setLayoutManager(new LinearLayoutManager(ProjectRadioListActivity.this));
        ycRefreshView.setEmptyView(R.layout.empty_view_layout);
        ycRefreshView.setAdapter(mAdapter);
        //设置上拉加载更多时布局，以及监听事件
        mAdapter.setMore(R.layout.view_more, () -> {
            //可以做请求下一页操作
            mPageNum++;
            refresh = false;
            getReaderList();
        });
        ycRefreshView.setRefreshListener(() -> {
            mPageNum = 1;
            refresh = true;
            getReaderList();
        });
        mAdapter.setOnItemClickListener(position -> {
            ProjectListEntity.List reader = mAdapter.getAllData().get(position);
            Intent intent;
            if (reader.getType().equals("2")) {
                intent = new Intent(ProjectRadioListActivity.this, VideoActivity.class);
                intent.putExtra("TAG", TAG);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            } else if (reader.getType().equals("3")) {
                intent = new Intent(ProjectRadioListActivity.this, RadioActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            } else {
                intent = new Intent(ProjectRadioListActivity.this, ArticleActivity.class);
            }
            intent.putExtra("ReaderId", reader.getReaderId());
            startActivity(intent);
        });
        ycRefreshView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                final LinearLayoutManager layoutManager = (LinearLayoutManager) ycRefreshView.getRecyclerView().getLayoutManager();
                /*int pos = layoutManager.findFirstCompletelyVisibleItemPosition();//获取第一个先是的View的索引
                if (pos > 1) {
                    tv_title.setVisibility(View.VISIBLE);
                    tv_title.setText(readerType.getName());
                } else {
                    tv_title.setVisibility(View.INVISIBLE);
                }*/
            }
        });

        mAdapter.setOnItemChildClickListener((view, position) -> {
            //CollectionList.List collection = adapter.getAllData().get(position);
            switch (view.getId()) {
                case R.id.iv_icon:
                    JCRadioPlayer.releaseAllVideos();
                    CheckBox ic_play = (CheckBox) view;
                    setRadio(position);
                    mAdapter.setPlayPosition(position,ic_play.isChecked());
                    if (ic_play.isChecked()) {
                        if(check_play!=null){
                            check_play.setChecked(true);
                        }
                        mPlayPosition = position;
                    }else{
                        if(mPlayPosition==position &&check_play!=null){
                            hideFloat();
                            check_play.setChecked(false);
                        }
                    }
                    mMainHander.postDelayed(() -> {
                        plarRadio(ic_play.isChecked(),position);
                        mAdapter.notifyDataSetChanged();
                    },400);
                    break;
            }
        });
    }

    private int mLastPosition;
    private Handler mMainHander=new Handler();

    private void getReaderList() {
        Log.d("zhiqiang","getReaderList",new Throwable());
        showLoading("加载中");
        HashMap postMap = new HashMap();
        if(readerstyle==null){
            postMap.put("readerTypeId",String.valueOf(readerType.getReaderTypeId()));
        }else if(readerstyle!=null){
            postMap.put("readerStyleId",String.valueOf(readerstyle.getReaderStyleValue().getReaderStyleId()));
            postMap.put("readerStyleValueId",String.valueOf(readerstyle.getReaderStyleValue().getReaderStyleValueId()));
        }else if(mReaderTypeId!=0){
            postMap.put("readerTypeId",String.valueOf(mReaderTypeId));
        }
        String url = Urls.getReaderList(mPageNum, 10, mOrder);
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(url, postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                hideLoading();
            }

            @Override
            public void onSuccess(Request request, String result) {
                hideLoading();
                ProjectListEntity readerLists = gson.fromJson(result, ProjectListEntity.class);
                if (readerLists.getCode() == 0) {
                    totalPage = readerLists.getPage().getTotalPage();
                    if (refresh) {
                        mAdapter.removeAllHeader();
                        //mAdapter.addHeader(setInterItemView());
                        mAdapter.clear();
                    }
                   /* for (int i = 0; i < readerLists.getPage().getList().size(); i++) {
                        mAdapter.add(readerLists.getPage().getList().get(i));
                    }*/
                    mAdapter.addAll(readerLists.getPage().getList());
                    if (mPageNum >= totalPage) {
                        mAdapter.pauseMore();
                    }
                    if (readerstyle != null) {
                        mAdapter.setReaderStyle(readerstyle);
                    } else {
                        mAdapter.setReaderType(readerType);
                    }
                }
                mAdapter.notifyDataSetChanged();
                radioInfoList = mAdapter.getAllData();
                try{
                    for(int i=0;i<radioInfoList.size();i++){
                        if(JCMediaManager.instance().mediaPlayer.isPlaying() && JCMediaManager.instance().CURRENT_PLAYING_URL.equals(radioInfoList.get(i).getUrl())){
                            check_play.setChecked(true);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    private CheckBox check_play;

   /* private InterItemView setInterItemView() {
        InterItemView interItemView = new InterItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_project_radio_type_list_title, parent, false);
                return view;
            }

            @Override
            public void onBindView(View headerView) {
                TextView tv_title_top = headerView.findViewById(R.id.tv_title_top);
                TextView tv_content = headerView.findViewById(R.id.tv_content);
                TextView tv_section = headerView.findViewById(R.id.tv_section);
                check_play = headerView.findViewById(R.id.check_play);
                TextView tv_new_update=headerView.findViewById(R.id.tv_new_update);
                TextView tv_noramal_sort=headerView.findViewById(R.id.tv_noramal_sort);
                check_play.setOnCheckedChangeListener((buttonView, isChecked) -> {
                    setRadio(mPlayPosition);
                    plarRadio(isChecked,mPlayPosition);
                    mAdapter.setPlayPosition(mPlayPosition,isChecked);
                    mAdapter.notifyDataSetChanged();
                });
                //CheckBox iv_down=headerView.findViewById(R.id.cb_down);
                setText(tv_title_top, readerType.getName());
                setText(tv_content, readerType.getSynopsis());
                setText(tv_section, "共" + readerType.getTotal() + "课");
                tv_new_update.setOnClickListener(v -> {
                    refresh=true;
                    mOrder="desc";
                    getReaderList();
                });
                tv_noramal_sort.setOnClickListener(v -> {
                    refresh=true;
                    mOrder="asc";
                    getReaderList();
                });
               *//* iv_down.setOnCheckedChangeListener((buttonView, isChecked) -> {
                    if(isChecked){
                        tv_content.setVisibility(View.VISIBLE);
                    }else {
                        tv_content.setVisibility(View.GONE);
                    }
                });*//*
                //ImageLoaderUtils.setImage(readerType.getIcon(),iv_title);
            }
        };
        return interItemView;
    }*/

    private void setText(TextView textView, String content) {
        if (content != null && textView != null) {
            textView.setText(content);
        }
    }

    private void setRadio(int position) {
        /*mJcVideoPlayerStandard.setUp(radioInfoList.get(0).getUrl()
                , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL);*/
        List<String> urlList = new ArrayList<>();
        for (int i = 0; i < radioInfoList.size(); i++) {
            urlList.add(radioInfoList.get(i).getUrl());
        }
        mJcVideoPlayerStandard.setUp(urlList
                , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, position);
        int codec = getIntent().getIntExtra("mediaCodec", AVOptions.MEDIA_CODEC_SW_DECODE);
        AVOptions options = new AVOptions();
        // the unit of timeout is ms
        options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 10 * 1000);
        // 1 -> hw codec enable, 0 -> disable [recommended]
        options.setInteger(AVOptions.KEY_MEDIACODEC, codec);
        options.setInteger(AVOptions.KEY_LIVE_STREAMING, mIsLiveStreaming ? 1 : 0);
        boolean disableLog = getIntent().getBooleanExtra("disable-log", false);
        options.setInteger(AVOptions.KEY_LOG_LEVEL, disableLog ? 5 : 0);
        boolean cache = getIntent().getBooleanExtra("cache", false);
        if (!mIsLiveStreaming && cache) {
            options.setString(AVOptions.KEY_CACHE_DIR, Urls.getFilePath());
        }
        boolean vcallback = getIntent().getBooleanExtra("video-data-callback", false);
        if (vcallback) {
            options.setInteger(AVOptions.KEY_VIDEO_DATA_CALLBACK, 1);
        }
    }

    private void plarRadio(boolean isChecked,int position) {
        if (isChecked) {
            showFloat(radioInfoList.get(position).getCover(),radioInfoList.get(position).getTitle(),
                    radioInfoList.get(position).getReaderId());
            mJcVideoPlayerStandard.playRadio();
            PrefUtils.putBoolean(MyApplication.isPlayingKey,false);
            PrefUtils.putString(MyApplication.isPlayingUrl,"");
        } else {
            mJcVideoPlayerStandard.pauseRadio();
        }
    }

    @Override
    public void setPosition(int position) {
        mPlayPosition=position;
    }
}
